import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Space,
  DatePicker,
  Table,
  Tag,
  message,
  Modal,
} from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { delArticle, getArticleList } from 'api/article';
import ErrorImg from 'assets/error.png';
import ChannelSelect from 'components/ChannelSelect';
const { RangePicker } = DatePicker;
export default function ArticleList(props) {
  const [articleList, setArticleList] = useState([]);
  const [formDate, setFormDate] = useState([]);
  const pageRef = useRef();
  // 获取文章列表
  const getArticle = async (params) => {
    const res = await getArticleList(params);
    // console.log(res);
    setArticleList(res.data);
  };
  // 筛选按钮
  const onFinish = (val) => {
    // console.log(23, val);
    let formData = {
      ...val,
    };
    if (formData.status === -1) {
      delete formData.status;
    }
    if (formData.date) {
      const begin_pubdate = formData.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const end_pubdate = formData.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      formData.begin_pubdate = begin_pubdate;
      formData.end_pubdate = end_pubdate;
      delete formData.date;
    }
    // 去除undefined的值
    formData = JSON.parse(JSON.stringify(formData));
    setFormDate(formData);
    // console.log('formData', formData);
    getArticle(formData);
  };
  // 分页
  const onChange = (page, per_page) => {
    // console.log(page, per_page);
    pageRef.current = { page, per_page };
    getArticle({ page, per_page, ...formDate });
  };
  useEffect(() => {
    getArticle();
  }, []);
  // 删除按钮
  const delFn = async (id) => {
    // console.log(id);
    Modal.confirm({
      title: '温馨提示',
      content: (
        <div>
          <p>确定要删除？</p>
        </div>
      ),
      onOk: async () => {
        await delArticle(id);
        if (articleList.results.length === 1 && pageRef.current.page > 1) {
          pageRef.current.page--;
        }
        getArticle({ ...pageRef.current, ...formDate });
        message.success('删除成功');
      },
    });
  };
  // 编辑按钮
  const editFn = (id) => {
    // console.log(id);
    props.history.push(`/edit/${id}`);
  };
  // 标签颜色和名字
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  // 列表行数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      render: (value, record) => {
        // console.log(record);
        // record代表着整个数据对象
        return record.cover.images.length ? (
          <img src={record.cover.images[0]} alt="" width={100} height={60} />
        ) : (
          <img src={ErrorImg} alt="" width={100} height={60} />
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (value, record) => {
        const currentItem = articleStatus.find(
          (item) => item.id === record.status
        );
        return <Tag color={currentItem.color}>{currentItem.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            onClick={() => {
              editFn(record.id);
            }}
          />
          <Button
            danger
            shape="circle"
            icon={<DeleteOutlined />}
            onClick={() => {
              delFn(record.id);
            }}
          />
        </Space>
      ),
    },
  ];
  return (
    <div
      className="articleList"
      style={{ height: 'calc (100vh - 64px)', overflow: 'auto', padding: 24 }}
    >
      <Card
        title={
          <Breadcrumb separator="/">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/*筛选列表 */}
        <Form initialValues={{ status: -1 }} onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <ChannelSelect></ChannelSelect>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        {/* 文章表格 */}
        <p>根据筛选条件共查询到{articleList.total_count}条数据</p>
        <Table
          columns={columns}
          dataSource={articleList.results}
          rowKey="id"
          pagination={{
            position: ['bottomCenter'],
            total: articleList.total_count,
            pageSize: articleList.per_page,
            page: articleList.page,
            // showSizeChanger: false,
            onChange: onChange,
          }}
        ></Table>
      </Card>
    </div>
  );
}
